package com.yf.compareYFJX;

import javax.net.ssl.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

public class HttpUtils {
    private static class TrustAnyTrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }
    }

    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    private static final String DEF_CHARSET = "utf-8";
    private String url;
    private int timeout;
    private boolean keepAlive;

    public HttpUtils(String url, int timeout, boolean keepAlive) {
        this.url = url;
        this.timeout = timeout;
        this.keepAlive = keepAlive;
    }

    public String get() throws IOException {
        return this.handle("GET", null, null);
    }

    public String get(Map<String, String> header) throws IOException {
        return this.handle("GET", header, null);
    }

    public String post(String body) throws IOException {
        return this.handle("POST", null, body);
    }

    public String post(Map<String, String> header, String body) throws IOException {
        return this.handle("POST", header, body);
    }

    public String put(Map<String, String> header, String body) throws IOException {
        return this.handle("PUT", header, body);
    }

    public String delete(Map<String, String> header, String body) throws IOException {
        return this.handle("DELETE", header, body);
    }

    private String handle(String method, Map<String, String> header, String body) throws IOException {
        URL url2 = new URL(url);
        HttpURLConnection conn = isHttps(url2) ? getHttpsConn(url2) : (HttpURLConnection) url2.openConnection();

        // socket settings
        conn.setRequestMethod(method);
        conn.setInstanceFollowRedirects(false);
        if (!"GET".equalsIgnoreCase(method)) {
            conn.setDoOutput(true);
        }
        conn.setDoInput(true);
        conn.setReadTimeout(timeout);
        conn.setConnectTimeout(timeout);
        conn.setUseCaches(false);
        if (keepAlive) {
            conn.setRequestProperty("Connection", "Keep-Alive");
        } else {
            conn.setRequestProperty("Connection", "close");
        }

        // write header
        if (header != null) {
            for (Map.Entry<String, String> entry : header.entrySet()) {
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }

        // write body
        if (body != null && body.trim().length() != 0) {
            byte[] data = body.getBytes(DEF_CHARSET);
            if (this.isEmpty(conn.getRequestProperty("Content-Type"))) {
                conn.setRequestProperty("Content-Type", "application/json; charset=" + DEF_CHARSET);
            }
            conn.setRequestProperty("Content-Length", String.valueOf(data.length));
            conn.getOutputStream().write(data);
        }

        int status = conn.getResponseCode();
        String result = null;
        if (status >= 200 && status < 400) {
            result = this.doRead(conn.getInputStream());
            conn.disconnect();
            return result;
        } else {
            result = this.doRead(conn.getErrorStream());
            conn.disconnect();
            throw new IOException(result);
        }
    }

    private HttpsURLConnection getHttpsConn(URL url) {
        SSLSocketFactory sslSocketFactory = this.getSSLSocketFactory();
        try {
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(sslSocketFactory);
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            return conn;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private SSLSocketFactory getSSLSocketFactory() {
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new SecureRandom());
            return sc.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private String doRead(InputStream is) throws IOException {
        byte[] buf2 = new byte[1024];
        ByteArrayOutputStream baos = new ByteArrayOutputStream(4 * 1024);
        for (int num; (num = is.read(buf2)) != -1; ) {
            baos.write(buf2, 0, num);
        }
        return baos.toString(DEF_CHARSET);
    }

    private boolean isHttps(URL url) {
        return url.getProtocol().equalsIgnoreCase("https");
    }

    private boolean isEmpty(String str) {
        return str == null || str.isEmpty();
    }

}